package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.*;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.serivce.ICashierBillService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
public class CashierBillServiceImpl implements ICashierBillService {
    //挂单逻辑
    @Autowired
    private CashierBillMapper mapper; //账单mapper
    @Autowired
    private CashierBillitemMapper billitemMapper; //账单明细mapper
    @Autowired
    private MemberMapper memberMapper; //会员的mapper
    @Autowired
    private RechargeTimeMapper rechargeTimeMapper; //会员充值次数的mapper
    @Autowired
    private ProductMapper productMapper; //商品的mapper
    @Autowired
    private AccountMapper accountMapper;//销售帐

    @Override
    public void deleteByPrimaryKey(Long id) {
        mapper.deleteByPrimaryKey(id);
    }
    //挂单
    @Override
    public void onAccount(CashierBill record) {
        //false证明是挂单
        //1.记录销售人,会员卡号
        Employee currentuser = UserContext.getCurrentuser();
        record.setSaleman(currentuser);
        //2.挂单时间
        record.setVdate(new Date());
        //设置单据状态 挂单
        record.setState(false);
        //3.关联收银明细
        //创建Bill的总数及总价格
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalNumber = BigDecimal.ZERO;
        List<CashierBillitem> items = record.getItems();
        //获取会员
        for (CashierBillitem item : items) {
            //6.计算会员价(销售价),存入salePrice num
            //8.计算总价,存入
            //设置单品总价格=单价*数量 四舍五入保留两位小数
            BigDecimal number = item.getNumber();
            BigDecimal amount = item.getNumber().multiply(item.getSalePrice()).setScale(2, RoundingMode.HALF_UP);
            totalAmount = totalAmount.add(amount);
            totalNumber = totalNumber.add(number);
        }
        //设置收银单据的总额和总数量
        record.setSaleAmmount(totalAmount);
        record.setNumber(totalNumber);
        mapper.insert(record);
        for (CashierBillitem item : items) {
            //保存明细到数据库 ()设置已经获取到的自增长id
            item.setBill_id(record.getId());
            billitemMapper.insert(item);
        }
    }
    //付款
    @Override
    public void pay(CashierBill record) {
        //公用信息
        Employee currentuser = UserContext.getCurrentuser();
        String cardNumber = record.getMember().getCardNumber();//获取会员卡号
        Member member = memberMapper.selectMemberInfoByCardNum(cardNumber);//获取当前的会员信息
        Date date = new Date();//当前时间
        //true证明是付款成功
        //1.记录销售人
        record.setSaleman(currentuser);
        //2.挂单时间
        record.setVdate(date);
        //设置单据状态 已付款 商品出库: 创建销售单
        record.setState(true);
        //创建Bill的总数及总价格
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalNumber = BigDecimal.ZERO;
        //创建会员的真实消费
        BigDecimal memberpay = BigDecimal.ZERO;
        for (CashierBillitem item : record.getItems()) {
            Product product = productMapper.selectByPrimaryKey(item.getProduct().getId());
            //设置单品总价格=单价*数量 四舍五入保留两位小数
            BigDecimal number = item.getNumber();
            BigDecimal amount = item.getNumber().multiply(item.getSalePrice()).setScale(2, RoundingMode.HALF_UP);
            totalAmount = totalAmount.add(amount);
            totalNumber = totalNumber.add(number);

            if ("服务".equals(product.getClassify())) {
                Integer time = rechargeTimeMapper.getTimeByPrimaryKey(cardNumber); //会员充值的次数
                int times = number.intValue();
                time=time-times;
                if (time < 0) { //如果没有库存,报错无商品
                    String msg = "会员["+member.getName()+"]没有["+product.getName()+"]的使用次数";
                    throw new RuntimeException(msg);
                }
                //如果商品类型是服务则减少会员次数
                rechargeTimeMapper.updateTimeByCardNum(time,cardNumber);
            }else{
                //如果不是消费次数,那么则扣除会员的存款
                memberpay = memberpay.add(amount);
            }
            //======================================销售帐循环叠加==============================================
            Account account = new Account();
            account.setCostAmmount(number.multiply(product.getCostPrice()).setScale(2, RoundingMode.HALF_UP));
            account.setCostPrice(product.getCostPrice());
            account.setMember(member);
            account.setProduct(product);
            account.setNum(number);
            account.setSaleAmmount(amount);
            account.setSalePrice(product.getSalePrice());
            account.setVdate(date);
            account.setSaleman(currentuser);
            accountMapper.insert(account); //保存销售帐
        }
        //4.扣除会员的存款
        //获取会员余额
        BigDecimal balance = member.getBalance().subtract(memberpay);
        member.setBalance(balance); //更新用户余额
        if (balance.intValue() < 0) { //如果没有库存,报错无商品
            String msg = "会员["+member.getName()+"]余额不足";
            throw new RuntimeException(msg);
        }
        //5.增加会员的积分
        int points = balance.intValue();//获取积分
        member.setPoints(points);
        //=====================================会员信息=============================================
        memberMapper.updateBalanceByPrimaryKey(member);
        //=====================================会员次数信息=============================================
        //循环中处理
        //======================================收银帐==============================================
        //设置收银单据的总额和总数量
        record.setSaleAmmount(totalAmount);
        record.setNumber(totalNumber);
        mapper.insert(record);
        //======================================收银明细==============================================
        for (CashierBillitem item : record.getItems()) {
            //保存明细到数据库 ()设置已经获取到的自增长id
            item.setBill_id(record.getId());
            billitemMapper.insert(item);
        }
        //付款之后删除挂单信息
        mapper.deleteOnAccountByCardNumber(record.getMember().getCardNumber());
        billitemMapper.deleteByPrimaryKey(record.getId());
    }
    //取单
    @Override
    public List<CashierBillitem> selectByPrimaryKey(String cardNumber) {
        //取单之前删除以前的挂单
        Long id = mapper.selectByCarNumber(cardNumber);
        List<CashierBillitem> cashierBillitems = billitemMapper.selectItemsByBillId(id);
        return cashierBillitems;
    }

    @Override
    public PageResult query(QueryObject qo) {
        return null;
    }

    @Override
    public PageResult selectAll() {
        Integer total = mapper.count();
        if (total > 0) {
            List<CashierBill> rows = mapper.selectAll();

            return new PageResult(total,rows);
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }
}
